<template>
	<div class="app-container">
		<div class="filter-container">
			<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="addArticle">添加文章</el-button>
			<el-dialog :title="thisType == 'add' ? '添加文章' : '编辑文章'" :visible.sync="dialogFormVisible" :fullscreen="fullscreen">
				<el-form ref="dataForm" :model="form" label-position="right">
					<el-form-item label="文章标题" :label-width="formLabelWidth">
						<el-input v-model="form.title" autocomplete="off" placeholder="请输入文章标题"></el-input>
					</el-form-item>
					<el-form-item label="B站获取" :label-width="formLabelWidth">
						<el-input v-model="form.robot" placeholder="aid" autocomplete="off" style="width:20%;"></el-input>
						<el-input v-model="form.cid" placeholder="cid(可选)" autocomplete="off" style="width:20%;"></el-input>
						<el-input v-model="form.page" placeholder="page(可选)" autocomplete="off" style="width:80px;"></el-input>
						<el-button type="primary" @click="getFromBilibili">获取</el-button>
					</el-form-item>
					<el-form-item label="栏目" :label-width="formLabelWidth">
						<el-select v-model="form.columnId" placeholder="请选择文章所属栏目" :width="400">
							<el-option v-for="column in columnList" :label="column.title" :value="column.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="发布时间" :label-width="formLabelWidth">
						<el-date-picker v-model="form.publishTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
					</el-form-item>
					<el-form-item label="缩略图地址" :label-width="formLabelWidth">
						<el-input v-model.number="form.imgURL" autocomplete="off" placeholder="请输入缩略图地址"></el-input>

						<el-upload
							class="upload-demo"
							:action="domain"
							:data="QiniuData"
							:on-preview="handlePreview"
							:on-remove="handleRemove"
							:on-success="uploadSuccess"
							:on-error="uploadError"
							:before-upload="beforeAvatarUpload"
							:before-remove="beforeRemove"
							:limit="1"
							:on-exceed="handleExceed"
							:file-list="fileList"
						>
							<el-button size="small" type="primary" @click="uploadImg">上传缩略图</el-button>
						</el-upload>
					</el-form-item>
					<el-form-item label="文章摘要" prop="abstract" :label-width="formLabelWidth"><el-input type="textarea" v-model="form.abstract"></el-input></el-form-item>
					<el-form-item label="文章内容" :label-width="formLabelWidth"><tinymce ref="editor" v-model="form.content" :height="300" /></el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					
					<el-button @click="dialogFormVisible = false">取 消</el-button>
					<el-button type="primary" @click="clickOK(false)">保 存</el-button>
					<el-button type="primary" @click="clickOK(true)">确 定</el-button>
				</div>
			</el-dialog>

			<el-table border :data="tableData" style="width: 100%">
				<el-table-column prop="title" label="文章标题"></el-table-column>
				<el-table-column prop="column.title" label="所属栏目" width="180"></el-table-column>
				<el-table-column prop="publishTime" label="发布时间" width="280">
					<template slot-scope="scope">
						<i class="el-icon-time"></i>
						<span style="margin-left: 10px">{{ scope.row.publishTime | dateformat('YYYY-MM-DD HH:mm:ss') }}</span>
						<el-tag v-if="scope.row.hasEdit==false" type="success">抓取</el-tag>
					</template>
					
				</el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-button size="mini" @click="editArticle(scope.row)">编辑</el-button>
						<el-button size="mini" type="danger" @click="deleteArticle(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@current-change="handleCurrentChange"
				:current-page.sync="currentPage"
				:page-size="pageSize"
				layout="prev, pager, next, jumper"
				:total="total"
			></el-pagination>
		</div>
	</div>
</template>

<script>
import Tinymce from '@/components/Tinymce';

import { createArticle, getArticleList, getArticleListCount, getOneArticle, updateArticle, getFromBilibili, uptokenURL,updateFromBilibili } from '@/api/article';
import { getColumnList } from '@/api/column';
export default {
	components: {
		Tinymce
	},
	data() {
		return {
			thisType: 'add',
			dialogFormVisible: false,
			formLabelWidth: '120px',
			fullscreen: true,
			fileList: [],
			form: {
				title: '',
				columnId: '',
				publishTime: '',
				content: '',
				imgURL: '',
				abstract: '',
				robot: ''
			},
			total: 0,
			pageSize: 10,
			pageCount: 0,
			currentPage: 1,
			tableData: [],
			columnList: [],
			imgName: "",
			QiniuData: {
				key: '', //图片名字处理
				token: '' //七牛云token
			},
			domain: 'https://upload-z2.qiniup.com', // 七牛云的上传地址（华南区）
			qiniuaddr: process.env.VUE_APP_QINIU_IMAGEURL // 七牛云的图片外链地址
		};
	},
	created() {
		this.initData();
		this.getColumnList();
	},
	methods: {
		initData() {
			this.getListCount();
		},
		resetTemp() {
			this.form = {
				title: '',
				columnId: '',
				publishTime: '',
				content: ''
			};
			this.fileList = [];
			console.log(this.$refs.editor);
			if(this.$refs.editor){
				this.$refs.editor.setContent('');
			}
			
		},
		getListCount() {
			getArticleListCount({
				where: {
					state: 0
				}
			})
				.then(response => {
					console.log(response);
					this.total = response.count;
					this.pageCount = Math.ceil(this.total / this.pageSize);
					this.getList(this.currentPage, this.pageSize);
				})
				.catch(error => {
					this.$message({
						message: error,
						type: 'error'
					});
				});
		},
		getList(currentPage, pageSize) {
			getArticleList({
				filter: {
					where: {
						state: 0
					},
					fields: {
						content: false,
						id: true,
						title: true,
						publishTime: true,
						columnId: true,
						hasEdit:true
					},
					order: 'publishTime DESC',
					limit: pageSize,
					skip: (currentPage - 1) * pageSize,
					include: {
						relation: 'column', // include the column object
						scope: {
							// further filter the owner object
							fields: {
								content: false,
								id: true,
								title: true,
								weight: true
							}
						}
					}
				}
			})
				.then(response => {
					console.log(response);
					this.tableData = response;
				})
				.catch(error => {
					this.$message({
						message: error,
						type: 'error'
					});
				});
		},
		getColumnList() {
			getColumnList({
				filter: {
					where: {
						state: 0
					},
					fields: {
						content: false,
						id: true,
						title: true,
						weight: true
					},
					order: 'weight DESC'
				}
			})
				.then(response => {
					console.log(response);
					this.columnList = response;
				})
				.catch(error => {
					this.$message({
						message: error,
						type: 'error'
					});
				});
		},
		addArticle() {
			this.thisType = 'add';
			// this.dialogStatus = 'create'
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.resetTemp();
				this.$refs['dataForm'].clearValidate();
			});
		},
		editArticle(article) {
			this.thisType = 'edit';
			this.resetTemp();
			getOneArticle(article.id, {})
				.then(response => {
					console.log(response);
					this.form = response;
					if (response.imgURL&&response.imgURL.split('_').length>1) {
						this.timestamp = response.imgURL.split('_')[1].split('.')[0];
					}
					console.log(this.timestamp);
					this.dialogFormVisible = true;
					this.$nextTick(() => {
						this.$refs.editor.setContent(response.content);
					});
				})
				.catch(error => {
					this.$message({
						message: error,
						type: 'error'
					});
				});
		},
		deleteArticle(article) {
			this.$confirm('将要删除该文章, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					var _article = article;
					_article.state = 1;
					updateArticle(_article)
						.then(response => {
							console.log(response);
							this.$message({
								type: 'success',
								message: '删除成功!'
							});
							this.initData();
						})
						.catch(error => {
							this.$message({
								message: error,
								type: 'error'
							});
						});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
		},
		clickOK(close) {
			if (this.thisType == 'add') {
				this.postArticle();
			} else if (this.thisType == 'edit') {
				this.updateArticle(close);
			}
		},
		updateArticle(close) {
			console.log(this.form);
			this.form.hasEdit=true;
			updateArticle(this.form)
				.then(response => {
					console.log(response);
								
					this.$message({
						message: '编辑文章成功',
						type: 'success'
					});
					if(close){
						this.dialogFormVisible = false;
						this.initData();
					}		
					
				})
				.catch(error => {
					this.$message({
						message: error,
						type: 'error'
					});
				});
			console.log(this.form);
			//
		},
		postArticle() {
			createArticle(this.form)
				.then(response => {
					console.log(response);
					this.dialogFormVisible = false;
					this.$message({
						message: '添加文章成功',
						type: 'success'
					});
					this.initData();
				})
				.catch(error => {
					this.$message({
						message: error,
						type: 'error'
					});
				});
			console.log(this.form);
			//
		},
		uploadImg() {
			uptokenURL()
				.then(response => {
					this.QiniuData.token = response.uptoken;
				})
				.catch(error => {
					this.$message({
						message: error,
						type: 'error'
					});
				});
		},

		beforeAvatarUpload(file) {
			var name = file.name;
			var index = name.lastIndexOf('.');
			var suffix = name.substring(index + 1);
			this.imgName='cms_' + new Date().getTime(),
			this.QiniuData.key = this.imgName + '.' + suffix;
			// this.QiniuData.key = `upload_pic_${file.name}`;
		},
		uploadSuccess(response, file, fileList) {
			console.log(this.qiniuaddr);
			console.log(response.key);
			console.log(this.form)
			// this.form.imgURL = this.qiniuaddr.toString() + response.key;
			this.$set(this.form, 'imgURL', this.qiniuaddr + response.key)
		},
		uploadError(err, file, fileList) {
			this.$message({
				message: '上传出错，请重试！',
				type: 'error',
				center: true
			});
		},
		//移除上传图片
		handleRemove(file, fileList) {
			console.log(file, fileList);
			this.form.imgURL = '';
		},
		//点击文件列表中已上传的文件时的钩子
		handlePreview(file) {
			console.log(file);
		},
		//文件超出个数限制时的钩子
		handleExceed(files, fileList) {
			console.log(fileList);
			this.$message.warning(`只能上传一个缩略图，请移除后替换。`);
		},
		//删除文件之前的钩子
		beforeRemove(file, fileList) {
			return this.$confirm(`确定移除 ${file.name}？`);
		},
		getFromBilibili() {
			var id = this.form.robot; //'80094359'
			if (!id) {
				return this.$message({
					message: '请输入B站文章ID',
					type: 'error'
				});
			}
			id = id.replace('av', '');

			if (!id) {
				return this.$message({
					message: '请输入B站文章ID',
					type: 'error'
				});
			}
			if(this.form.cid){
				return this.updateFromBilibili([{cid:this.form.cid,page:this.form.page,part:this.form.title}])
			}
			// id=this.form.robot||'80094359';
			getFromBilibili({ id: id })
				.then(response => {
					console.log(response);
					if (response.data.code != 0) {
						return this.$message({
							message: response.data,
							type: 'error'
						});
					}
					var data = response.data.data;
					this.form.title = data.title;
					var newDate = new Date();
					newDate.setTime(data.ctime * 1000);
					this.form.publishTime = newDate;
					// this.form.imgURL=data.pic.replace('http://','http://')+'_320x200.jpg';
					this.form.imgURL = this.qiniuaddr + 'cms_' + data.aid + '.jpg';
					this.form.abstract = data.desc;
					var content = '<p>' + data.desc + '</p>';
					content +=
						'<p><iframe src="//player.bilibili.com/player.html?aid=' +
						id +
						'&amp;page=1" width="1100px" height="700px" frameborder="no" scrolling="no" allowfullscreen="allowfullscreen"> </iframe></p>';
					this.form.content = content;
					this.$refs.editor.setContent(content);
				})
				.catch(error => {
					this.$message({
						message: error,
						type: 'error'
					});
				});
		},
		updateFromBilibili(selectArticle) {
		
			updateFromBilibili({
					aid: this.form.robot,
					columnId: this.form.columnId,
					list: selectArticle
				})
				.then(response => {
					console.log(response);
					if (response.data.length == 0) {
						return this.$message({
							message: response.data,
							type: 'error'
						});
					}
					this.editArticle({id:this.form.id})
		
		
				})
				.catch(error => {
					this.$message({
						message: error,
						type: 'error'
					});
				});
		},
		handleCurrentChange(val) {
			this.currentPage = val;
			this.getList(this.currentPage, this.pageSize);
			console.log(`当前页: ${val}`);
		}
	}
};
</script>
